package com.example.steveaoblogdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.steveaoblogdemo.entity.Comment;
import com.example.steveaoblogdemo.mapper.CommentMapper;
import com.example.steveaoblogdemo.service.CommentService;
import com.example.steveaoblogdemo.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;


import javax.annotation.Resource;
import java.util.*;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    CommentMapper commentMapper;

    public int addComment(Integer id, Integer aId, String cName, String content, String createTime, Integer parentId,String reply){
        commentMapper.addComment(id,aId,cName,content,createTime,parentId,reply);
        return 0;
    }

    public Result<?> getCommentList(Integer aId){
        List<Comment> commentList = commentMapper.search(aId);
        Map<Integer,Comment> map = new HashMap<>();
        List<Comment> result = new ArrayList<>();
        //父评论写入
        for (Comment c:commentList){
            if (c.getParentId()==null){
                result.add(c);
            }
            map.put(c.getId(),c);
        }
        //子评论写入
        for (Comment c:commentList){
            if (c.getParentId()!=null){
                Comment parent = map.get(c.getParentId());
                if (parent == null){
                    continue;
                }
                if (parent.getId().intValue() == c.getId().intValue()){
                    continue;
                }
                if (parent.getChildList() == null){
                    parent.setChildList(new ArrayList<>());
                }
                parent.getChildList().add(c);
            }
        }
        return new Result<>(200,"查询成功",result);
    }

    public Result<?> deleteComment(Integer id){
        UpdateWrapper<Comment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id).set("a_id",1);
        int result = commentMapper.update(null,updateWrapper);
        return new Result<>(200,"删除成功",result);
    }
}
